package com.webemail.views.controller;

import com.alibaba.fastjson2.JSON;
import com.webemail.sys.model.*;
import com.webemail.sys.service.*;
import com.webemail.sys.util.CommonUtils;
import com.webemail.sys.util.MailConnect;
import com.webemail.sys.util.MailConnect.FolderType;
import com.webemail.sys.util.MailUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author LaiHQ
 */
@Controller
public class EmailControllerView {
	@Resource
	private EmailService emailService;
	@Resource
	private FolderService folderService;
	@Resource
	private LabelService labelService;
	@Resource
	private MessageDeletedService messageDeletedService;
	@Resource
	private MessageDraftsService messageDraftsService;
	@Resource
	private MessageFolderService messageFolderService;
	@Resource
	private MessageInboxService messageInboxService;
	@Resource
	private MessageJunkService messageJunkService;
	@Resource
	private MessageSendService messageSendService;
	private int getUserId() {
		return 1;
	}

	@RequestMapping("/emailWrite")
	public String emailWrite(HttpServletRequest request, Model model) {
		List<SysEmailAccount> list = emailService.list(this.getUserId());
		model.addAttribute("mailList", list);
		return "mail/email_write";
	}

	@RequestMapping("/emailDetail")
	public String emailDetail(HttpServletRequest request, Model model) {
		String id = null;
		try {
			id = CommonUtils.getString(request.getParameter("id"));
			int idTemp = Integer.parseInt(id);
			SysMessageInbox result = messageInboxService.get(idTemp, this.getUserId());
			model.addAttribute("message", result);
			model.addAttribute("mail_type", "INBOX");
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			this.readMessage(id, 1, FolderType.INFolder);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "mail/email_detail";
	}

	@RequestMapping("/emailReply")
	public String emailReply(HttpServletRequest request, Model model) {
		String messageId = CommonUtils.getString(request.getParameter("messageId"));
		String mailType = CommonUtils.getString(request.getParameter("mailType"));
		model.addAttribute("messageId", messageId);
		model.addAttribute("mailType", mailType);
		if (StringUtils.isBlank(messageId) || StringUtils.isBlank(mailType)) {
			model.addAttribute("msg", "信息不全");
			return "mail/error";
		}
		Long tempId = null;
		int userId = this.getUserId();
		try {
			tempId = Long.parseLong(messageId);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "信息出错");
			return "mail/error";
		}
		long mailId = 0;
		if (mailType.equalsIgnoreCase("INBOX")) {
			SysMessageInbox temp = messageInboxService.get(tempId, userId);
			mailId = temp.getMailId();
			model.addAttribute("message", temp);
		} else if (mailType.equalsIgnoreCase("Delete")) {
			SysMessageDeleted temp = messageDeletedService.get(tempId, userId);
			mailId = temp.getMailId();
			model.addAttribute("message", temp);
		} else if (mailType.equalsIgnoreCase("Drafts")) {
			SysMessageDrafts temp = messageDraftsService.get(tempId, userId);
			mailId = temp.getMailId();
			model.addAttribute("message", temp);
		} else if (mailType.equalsIgnoreCase("Folder")) {
			SysMessageFolder temp = messageFolderService.get(tempId, userId);
			mailId = temp.getMailId();
			model.addAttribute("message", temp);
		} else if (mailType.equalsIgnoreCase("Junk")) {
			SysMessageJunk temp = messageJunkService.get(tempId, userId);
			mailId = temp.getMailId();
			model.addAttribute("message", temp);
		} else if (mailType.equalsIgnoreCase("Send")) {
			SysMessageSend temp = messageSendService.get(tempId, userId);
			mailId = temp.getMailId();
			model.addAttribute("message", temp);
		}
		List<SysEmailAccount> list = emailService.list(this.getUserId());
		model.addAttribute("mailList", list);

		if (mailId > 0) {
			SysEmailAccount email = emailService.get(mailId, userId);
			System.out.println(JSON.toJSON(email));
			model.addAttribute("send", email);
		} else {
			model.addAttribute("msg", "信息不全");
			return "mail/error";
		}

		return "mail/email_reply";
	}

	@RequestMapping("/emailForward")
	public String emailForward(HttpServletRequest request, Model model) {
		String messageId = CommonUtils.getString(request.getParameter("messageId"));
		String mailType = CommonUtils.getString(request.getParameter("mailType")).trim();
		model.addAttribute("messageId", messageId);
		model.addAttribute("mailType", mailType);
		if (StringUtils.isBlank(messageId) || StringUtils.isBlank(mailType)) {
			model.addAttribute("msg", "信息不全");
			return "mail/error";
		}
		Long tempId = null;
		int userId = this.getUserId();
		try {
			tempId = Long.parseLong(messageId);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "信息出错");
			return "mail/error";
		}
		if (mailType.equalsIgnoreCase("INBOX")) {
			SysMessageInbox temp = messageInboxService.get(tempId, userId);
			model.addAttribute("message", temp);
		} else if (mailType.equalsIgnoreCase("Delete")) {
			SysMessageDeleted temp = messageDeletedService.get(tempId, userId);
			model.addAttribute("message", temp);
		} else if (mailType.equalsIgnoreCase("Drafts")) {
			SysMessageDrafts temp = messageDraftsService.get(tempId, userId);
			model.addAttribute("message", temp);
		} else if (mailType.equalsIgnoreCase("Folder")) {
			SysMessageFolder temp = messageFolderService.get(tempId, userId);
			model.addAttribute("message", temp);
		} else if (mailType.equalsIgnoreCase("Junk")) {
			SysMessageJunk temp = messageJunkService.get(tempId, userId);
			model.addAttribute("message", temp);
		} else if (mailType.equalsIgnoreCase("Send")) {
			SysMessageSend temp = messageSendService.get(tempId, userId);
			model.addAttribute("message", temp);
		}
		List<SysEmailAccount> list = emailService.list(this.getUserId());
		model.addAttribute("mailList", list);
		return "mail/email_forward";
	}

	@RequestMapping("/emailReviceALL")
	public String emailReviceALL(HttpServletRequest request, Model model) {
		long userId = this.getUserId();
		List<SysLabel> labelList;
		List<SysFolder> folderList;
		try {
			labelList = labelService.list(userId);
			folderList = folderService.list(userId);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", e.getMessage());
			return "mail/error";
		}
		model.addAttribute("labelList", labelList);
		model.addAttribute("folderList", folderList);
		return "mail/message_inbox_all";
	}

	@RequestMapping("/emailRevice")
	public String emailRevice(HttpServletRequest request, Model model) {
		long userId = this.getUserId();
		long mailId = 0;
		SysEmailAccount temp;
		List<SysLabel> labelList;
		List<SysFolder> folderList;
		try {
			mailId = Long.parseLong(CommonUtils.getString(request.getParameter("id")));
			temp = emailService.get(mailId, this.getUserId());
			labelList = labelService.list(userId);
			folderList = folderService.list(userId);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", e.getMessage());
			return "mail/error";
		}
		if (temp == null) {
			model.addAttribute("msg", "找不到邮箱");
			return "mail/error";
		}
		model.addAttribute("mailId", mailId);
		model.addAttribute("labelList", labelList);
		model.addAttribute("folderList", folderList);
		return "mail/message_inbox";
	}

	// start
	@RequestMapping("/emailSetting")
	public String emailSetting(HttpServletRequest request, Model model) {
		return "mail/setting";
	}

	@RequestMapping("/emailAddAccount")
	public String emailAddAccount(HttpServletRequest request, Model model) {
		return "mail/add_account";
	}

	@RequestMapping("/labelAdd")
	public String labelAdd(HttpServletRequest request, Model model) {
		return "mail/add_label";
	}

	@RequestMapping("/folderAdd")
	public String folderAdd(HttpServletRequest request, Model model) {
		return "mail/add_folder";
	}

	@RequestMapping("/emailEdit")
	public String emailEditAccount(HttpServletRequest request, Model model) {
		try {
			String id = CommonUtils.getString(request.getParameter("id"));
			int idTemp = Integer.parseInt(id);
			SysEmailAccount temp = emailService.get(idTemp, this.getUserId());
			model.addAttribute("email", temp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "mail/edit_account";
	}

	@RequestMapping("/labelEdit")
	public String labelEdit(HttpServletRequest request, Model model) {
		try {
			String id = CommonUtils.getString(request.getParameter("id"));
			int idTemp = Integer.parseInt(id);
			SysLabel temp = labelService.get(idTemp, this.getUserId());
			model.addAttribute("label", temp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "mail/edit_label";
	}

	@RequestMapping("/folderEdit")
	public String folderEdit(HttpServletRequest request, Model model) {
		try {
			String id = CommonUtils.getString(request.getParameter("id"));
			int idTemp = Integer.parseInt(id);
			SysFolder temp = folderService.get(idTemp, this.getUserId());
			model.addAttribute("folder", temp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "mail/edit_folder";
	}

	/**
	 *
	 * @param messageIds
	 * @param read
	 * @param folderType
	 * @return
	 */
	private boolean readMessage(String messageIds, int read, FolderType folderType) {
		long userId = this.getUserId();
		String messageId[] = messageIds.split(",");
		SysEmailAccount sysEmailAccount = null;
		MailConnect mailConnect = null;
		int count = 0;
		for (int i = 0; i < messageId.length; i++) {
			long tempId = Long.parseLong(messageId[i]);
			SysMessageInbox message = messageInboxService.get(tempId, userId);
			if (read == 0) {
				message.setHasRead("false");
			} else {
				message.setHasRead("true");
			}
			int result = messageInboxService.update(message);
			if (sysEmailAccount == null) {
				long mailId = message.getMailId();
				sysEmailAccount = emailService.get(mailId, userId);
				mailConnect = new MailConnect(MailUtils.getReMailBean(sysEmailAccount));
				// mailConnect.checkProperties();
				mailConnect.init();
				if (mailConnect.getState() != 0) {
					sysEmailAccount.setIsSubmit("false");
				}
			}
			if (sysEmailAccount != null) {
				if (sysEmailAccount.isSubmit()) {
					if (read == 0) {
						mailConnect.unReadMessage(folderType, message.getMessageId(), message.getSentDateTime());
					} else {
						mailConnect.readMessage(folderType, message.getMessageId(), message.getSentDateTime());
					}
				}
			}
			if (result > 0) {
				count++;
			}
		}
		if (mailConnect != null) {
			mailConnect.stop();
		}
		if (count == messageId.length) {
			return true;
		} else {
			return false;
		}
	}
}
